package com.ruoyi.common.utils.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Date;

@Component
public class MailAttachmentUtil {

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMail(String[] receiveUsers,  String title,String content,String folderName,String[] fileNames) {

        try {


            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // true表示构建一个可以带附件的邮件对象
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            helper.setSubject(title);

            helper.setFrom("ykyl@yikongenomics.com");
            helper.setTo(receiveUsers);
            helper.setSentDate(new Date());
            helper.setText(content, false);

            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 邮件内容设值
            BodyPart contentBody = new MimeBodyPart();
            contentBody.setContent(content, "text/html;charset=utf-8");
            multipart.addBodyPart(contentBody);

            // 第一个参数是文件名称，后缀需要加上，第二个参数是文件的位置

            if (folderName != null){
                if(fileNames[0] != null) {
                    BodyPart messageBodyPart = new MimeBodyPart();
                    // 设置要发送附件的文件路径
                    DataSource source = new FileDataSource(folderName + File.separator + fileNames[0]);
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    // 处理附件名称中文（附带文件路径）乱码问题
                    messageBodyPart.setFileName(source.getName());
                    multipart.addBodyPart(messageBodyPart);
                }
                if(fileNames.length > 1 && fileNames[1] != null){
                    BodyPart messageBodyPart = new MimeBodyPart();
                    // 设置要发送附件的文件路径
                    DataSource source = new FileDataSource(fileNames[1]);
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    // 处理附件名称中文（附带文件路径）乱码问题
                    messageBodyPart.setFileName(source.getName());
                    multipart.addBodyPart(messageBodyPart);
                }
            }
            mimeMessage.setContent(multipart);
        javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
